package com.peter.baselibrary.base;

import android.annotation.SuppressLint;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class BaseHolder extends RecyclerView.ViewHolder {
    public BaseHolder(View itemView) {
        super(itemView);

    }

    private SparseArray<View> mView = new SparseArray<View>();


    public <T extends View> T getView(int viewId) {
        View view = mView.get(viewId);
        if (view == null) {
            view = itemView.findViewById(viewId);
            mView.put(viewId, view);
        }
        return (T) view;
    }

    public <T extends ViewGroup> T getViewGroup(int viewId) {
        View view = mView.get(viewId);
        if (view == null) {
            view = itemView.findViewById(viewId);
            mView.put(viewId, view);
        }
        return (T) view;
    }

    @SuppressLint("SetTextI18n")
    public BaseHolder setText(int viewId, CharSequence text) {
        TextView view = getView(viewId);
        view.setText("" + text);
        return this;
    }

    public BaseHolder setHintText(int viewId, CharSequence text) {
        TextView view = getView(viewId);
        view.setHint("" + text);

        return this;
    }

    public BaseHolder setImageResource(int viewId, int resId) {
        ImageView imageView = getView(viewId);
        imageView.setImageResource(resId);
        return this;
    }

    public BaseHolder setImagePath(int viewId, HolderImageLoader imageLoader) {
        ImageView imageView = getView(viewId);
        imageLoader.loadImage(imageView, imageLoader.path);
        return this;
    }

    public BaseHolder setViewVisibility(int viewId, int visibility) {
        getView(viewId).setVisibility(visibility);
        return this;
    }

    public void setOnItemClickListener(View.OnClickListener listener) {

        itemView.setOnClickListener(listener);
    }

    public void setOnItemLongClickListener(View.OnLongClickListener longClickListener) {

        itemView.setOnLongClickListener(longClickListener);
    }

    abstract class HolderImageLoader {
        String path;

        HolderImageLoader(String path) {
            this.path = path;
        }

        abstract void loadImage(ImageView imageView, String path);
    }

}
